package com.example.demo.socket.handler;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.core.exception.ProgramException;
import com.example.demo.core.util.RegexUtil;
import com.example.demo.core.util.ThreadUtil;
import com.example.demo.socket.channelManager.MobileSocketManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author yj
 * @date 2021-07-24 23:26
 */
@Slf4j
@Component
public class SocketMessageHandler {

    @Async
    public void messageHandle(String shortId, JSONObject map) {
        if (RegexUtil.checkObjectIsNull(map)) {
            throw new ProgramException("Netty传递数据转换失败");
        }
        System.out.println("--------------------------" + ThreadUtil.getThreadName() + "------------------------------");
        System.out.println(shortId);
        String method = map.get("method").toString();
        switch (method) {
            case "pong":
                System.out.println(map.toJSONString());
                JSONObject result = new JSONObject();
                result.put("type", "ping");
                MobileSocketManager.writeAndFlush(shortId, result.toJSONString());
                break;
            default:
                System.out.println(map.toJSONString());
        }
    }

    /**
     * 客户端发：
     * {
     *     "method":"pong"
     * }
     *
     * 服务端回：
     * {
     *     "type":"ping"
     * }
     */
}
